<script setup>
import { onMounted, ref } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import ParkList from '@/components/parkList/index.vue'
import { Delete } from '@element-plus/icons-vue'
import { useTableList } from '@/hooks/useTableList'
import { useDict } from '@/hooks/useDict'
import vModal from '@/components/modal/index.vue'
import vForm from './form.vue'
import {
  getUserList,
  userAdd,
  userUpdateBatch,
  getUserDetail,
} from '@/api/manager/systemManage/user.js'
import { parkPageList } from '@/api/manager/dataManage/park'
import { useRoute, useRouter } from 'vue-router'
const router = useRouter()
const route = useRoute()

const searchParams = ref({
  type: ['1', '2', '3', '4'],
  isPatrol: 1,
  areaId: [],
  patrolPost: [],
})

const { dict, getDictValue } = useDict([
  'inspection_check_project_type',
  'inspection_inspection_type',
  'inspection_inspection_scene',
  'inspector_post_type',
])

const {
  Search,
  tableData,
  paginationParams,
  total,
  addRef,
  currentDetail,
  initTableList,
  handleSizeChange,
  handleReset,
  handleAdd,
  handleEdit,
  searchFromRef,
  handleClose,
} = useTableList(searchParams, getUserList)

const handleChangeStatus = async (row) => {
  return new Promise((resolve) => {
    ElMessageBox.confirm(`是否切换启用状态`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })
      .then(async () => {
        const detailRes = await getUserDetail({ pkid: row.pkid })
        const params = {
          userInfoAo: {
            ...detailRes.data.userInfo,
            userState: detailRes.data.userInfo.userState === 1 ? 0 : 1,
          },
          coreUserMetaInfo: detailRes.data.coreUserMetaInfo,
        }
        const res = await userAdd(params)
        if (res.success) {
          ElMessage.success('切换成功')
          resolve(true)
          initTableList()
        } else {
          ElMessage.error(res.message)
          resolve(false)
        }
      })
      .catch(() => {
        resolve(false)
      })
  })
}

const handleResetCustom = () => {
  const params = {
    type: ['1', '2', '3', '4'],
    isPatrol: 1,
    areaId: searchParams.value.areaId,
    patrolPost: [],
  }
  handleReset(params)
}

const handleChangePark = (val) => {
  if (val) {
    searchParams.value.areaId = [val]
  } else {
    searchParams.value.areaId = []
  }

  initTableList(1)
}

const multipleSelection = ref([])
const handleSelectionChange = (val) => {
  multipleSelection.value = val
}
const handleDelete = (row) => {
  let userIds = []
  if (row.pkid) {
    userIds = [row.pkid]
  } else {
    userIds = multipleSelection.value.map((i) => {
      return i.pkid
    })
  }
  ElMessageBox.confirm('是否确定删除该项？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(async () => {
      const params = {
        userIds: userIds,
        coreUserMetaInfo: {
          isPatrol: 0,
          areaId: '',
          patrolPost: '',
          checkType: '',
        },
      }
      const res = await userUpdateBatch(params)
      if (res.success) {
        ElMessage({
          type: 'success',
          message: '删除成功',
        })
        initTableList(1)
      } else {
        ElMessage.error(res.message)
      }
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '已取消删除',
      })
    })
}

onMounted(() => {
  // if (route.query) {
  //   console.log('route.query', route.query)
  //   searchParams.value = {
  //     ...searchParams.value,
  //     areaId: [route.query.areaId],
  //     patrolPost: [route.query.patrolPost],
  //     checkType: route.query.checkType,
  //   }
  // }
  initTableList(1)
})
</script>

<template>
  <div class="inspector-manage-form">
    <div class="body">
      <ParkList
        :current="searchParams.areaId.join(',')"
        @change="handleChangePark"
        :hasHidden="1"
      />
      <div class="right">
        <div class="custom-table-list-wrapper">
          <div class="search">
            <div class="search-left" ref="searchFromRef">
              <el-form class="search-form" inline>
                <el-form-item label="检查类型">
                  <el-select
                    class="search-select"
                    v-model="searchParams.checkType"
                    placeholder="请选择"
                    clearable
                  >
                    <el-option
                      v-for="(item, index) of dict[
                        'inspection_inspection_type'
                      ]"
                      :key="index"
                      :label="item.name"
                      :value="item.value"
                    />
                  </el-select>
                </el-form-item>
                <el-form-item label="岗位类型">
                  <el-select
                    class="search-select"
                    v-model="searchParams.patrolPost"
                    placeholder="请选择"
                    multiple
                    clearable
                  >
                    <el-option
                      v-for="(item, index) of dict['inspector_post_type']"
                      :key="index"
                      :label="item.name"
                      :value="item.value"
                    />
                  </el-select>
                </el-form-item>
                <el-form-item label="关键词">
                  <el-input
                    class="search-input"
                    v-model="searchParams.keywords"
                    placeholder="请输入人员名称"
                    :suffix-icon="Search"
                    clearable
                  ></el-input>
                </el-form-item>
              </el-form>
            </div>
            <div class="search-right">
              <el-button type="primary" @click="initTableList(1)"
                ><svg-icon name="search" size="14px" />搜索</el-button
              >
              <el-button @click="handleResetCustom"
                ><svg-icon name="reset" size="17px" />重置</el-button
              >
            </div>
          </div>
          <div class="content">
            <div class="content-operate">
              <el-button
                type="primary"
                @click="
                  handleAdd('新增巡检人员', {
                    areaId: searchParams.areaId.join(','),
                  })
                "
              >
                <svg-icon name="add" size="15px" />新增</el-button
              >
              <el-button type="primary" @click="handleDelete">
                <el-icon style="margin-right: 5px">
                  <Delete />
                </el-icon>
                批量移除
              </el-button>
            </div>
            <div class="content-table">
              <el-table
                class="custom-table"
                :data="tableData"
                @selection-change="handleSelectionChange"
              >
                <el-table-column type="selection" width="60px" />
                <el-table-column type="index" label="序号" width="60px" />
                <el-table-column prop="userName" label="人员名称" width="120" />
                <el-table-column prop="userPhone" label="联系方式" width="120">
                  <template #default="scope">
                    {{
                      scope.row.userPhone.replace(
                        /^(\d{3})(\d{4})(\d{4})$/,
                        '$1****$3',
                      )
                    }}
                  </template>
                </el-table-column>
                <el-table-column prop="checkType" label="检查类型">
                  <template #default="scope">
                    {{
                      getDictValue(
                        'inspection_inspection_type',
                        scope.row.checkType,
                        true,
                      )
                    }}
                  </template>
                </el-table-column>
                <el-table-column prop="patrolPost" label="岗位类型" width="120">
                  <template #default="scope">
                    {{
                      getDictValue('inspector_post_type', scope.row.patrolPost)
                    }}
                  </template>
                </el-table-column>
                <!-- <el-table-column
                  prop="inspectionCount"
                  label="巡检次数"
                  width="120"
                /> -->
                <el-table-column prop="userState" label="是否启用" width="100">
                  <template #default="scope">
                    <!-- {{ getDictValue('yn', scope.row.userState) }} -->
                    <el-switch
                      :active-value="1"
                      :inactive-value="0"
                      v-model="scope.row.userState"
                      :before-change="handleChangeStatus.bind(this, scope.row)"
                    />
                  </template>
                </el-table-column>
                <el-table-column label="操作" width="120px">
                  <template #default="scope">
                    <el-button
                      link
                      type="primary"
                      @click="handleEdit(scope.row, '编辑检查点')"
                      >编辑</el-button
                    >
                    <el-button
                      link
                      type="danger"
                      @click="handleDelete(scope.row)"
                      >删除</el-button
                    >
                  </template>
                </el-table-column>
              </el-table>
            </div>
            <div class="content-page">
              <el-pagination
                class="custom-pagination"
                :current-page="paginationParams.pageIndex"
                :page-size="paginationParams.pageSize"
                background
                :page-sizes="[10, 20, 30, 50]"
                layout="total, prev, pager, next, sizes, jumper"
                :total="total"
                @size-change="handleSizeChange"
                @current-change="initTableList"
              />
            </div>
          </div>
        </div>
      </div>
    </div>
    <!-- 弹窗 -->
    <v-form ref="addRef" :detail="currentDetail" @close="handleClose" />
  </div>
</template>

<style lang="scss" scoped>
@import '@/assets/styles/table.scss';

.content {
  .content-operate {
    display: flex;
    justify-content: flex-start;
  }
}

.inspector-manage-form {
  position: relative;

  width: 100%;
  height: 100%;
  border-radius: 4px;

  .body {
    position: relative;
    display: flex;
    justify-content: space-between;
    height: 100%;
  }

  .right {
    flex: 1;
    overflow: hidden;
  }
}
</style>
